// pages/membership-purchase/membership-purchase.js
Page({
  data: {
    selectedType: null,
    hasPurchasedFirstMonth: false,
    membershipExpiryDate: '加载中...'
  },

  onLoad() {
    const app = getApp();
    console.log('membership-purchase onLoad: 开始登录');
    app.doAutoLogin(true).then((res) => {
      console.log('onLoad: 登录成功，openID:', res.openID, 'token:', res.jwt_token.slice(0, 10) + '****');
      wx.setStorageSync('openID', res.openID);
      wx.setStorageSync('jwt_token', res.jwt_token);
      this.checkFirstMonthPurchase(res.openID, res.jwt_token);
      this.fetchMembershipExpiry(res.openID, res.jwt_token);
    }).catch((err) => {
      console.error('onLoad: 登录失败:', err);
      wx.showToast({ title: '登录失败，请重试', icon: 'none' });
      this.setData({ membershipExpiryDate: '加载失败' });
    });
  },

  selectMembership(e) {
    const type = e.currentTarget.dataset.type;
    this.setData({ selectedType: type });
    console.log('selectMembership: 选择会员类型:', type);
  },

  checkTokenValidity(jwtToken) {
    return new Promise((resolve, reject) => {
      try {
        if (!jwtToken || typeof jwtToken !== 'string' || !jwtToken.includes('.')) {
          console.error('Token 格式无效:', jwtToken);
          return this.refreshToken().then(resolve).catch(reject);
        }
        const payload = JSON.parse(atob(jwtToken.split('.')[1]));
        const exp = payload.exp * 1000;
        if (Date.now() > exp) {
          console.log('Token 已过期，尝试刷新');
          return this.refreshToken().then(resolve).catch(reject);
        }
        console.log('Token 有效:', jwtToken.slice(0, 10) + '****');
        resolve({ jwt_token: jwtToken });
      } catch (e) {
        console.error('解析 token 失败:', e);
        this.refreshToken().then(resolve).catch(reject);
      }
    });
  },

  refreshToken() {
    const app = getApp();
    console.log('refreshToken: 开始刷新 token');
    return app.doAutoLogin(true).then((res) => {
      wx.setStorageSync('jwt_token', res.jwt_token);
      wx.setStorageSync('openID', res.openID);
      console.log('Token 刷新成功:', res.jwt_token.slice(0, 10) + '****');
      return res;
    }).catch((err) => {
      console.error('刷新 token 失败:', err);
      wx.showToast({ title: '登录失败，请重试', icon: 'none' });
      throw err;
    });
  },

  checkFirstMonthPurchase(openID, jwtToken) {
    this.checkTokenValidity(jwtToken).then((result) => {
      const validToken = result.jwt_token;
      const baseUrl = getApp().getApiBaseUrl();
      console.log('checkFirstMonthPurchase: 请求 /payment/orders, token:', validToken.slice(0, 10) + '****');
      wx.request({
        url: `${baseUrl}/payment/orders?openID=${encodeURIComponent(openID)}`,
        method: 'GET',
        header: {
          'Authorization': `Bearer ${validToken}`,
          'Content-Type': 'application/json'
        },
        success: (res) => {
          console.log('checkFirstMonthPurchase: 响应:', res);
          if (res.statusCode === 200 && res.data.orders) {
            const hasPurchased = res.data.orders.some(order =>
              order.subject === 'First Month Membership' && order.status === 'SUCCESS'
            );
            this.setData({ hasPurchasedFirstMonth: hasPurchased });
            console.log('checkFirstMonthPurchase: hasPurchasedFirstMonth:', hasPurchased);
          } else if (res.statusCode === 401) {
            console.log('checkFirstMonthPurchase: 401，刷新 token');
            this.refreshToken().then((res) => {
              this.checkFirstMonthPurchase(res.openID, res.jwt_token);
            });
          } else {
            console.error('checkFirstMonthPurchase: 失败:', res.data);
            this.setData({ hasPurchasedFirstMonth: false });
          }
        },
        fail: (err) => {
          console.error('checkFirstMonthPurchase: 请求失败:', err);
          this.setData({ hasPurchasedFirstMonth: false });
          wx.showToast({ title: '加载订单失败', icon: 'none' });
        }
      });
    }).catch((err) => {
      console.error('checkFirstMonthPurchase: Token 验证失败:', err);
      this.setData({ hasPurchasedFirstMonth: false });
      wx.showToast({ title: '无法验证登录状态', icon: 'none' });
    });
  },

  fetchMembershipExpiry(openID, jwtToken) {
    this.checkTokenValidity(jwtToken).then((result) => {
      const validToken = result.jwt_token;
      const baseUrl = getApp().getApiBaseUrl();
      console.log('fetchMembershipExpiry: 请求 /user/settings, token:', validToken.slice(0, 10) + '****');
      wx.request({
        url: `${baseUrl}/user/settings?openID=${encodeURIComponent(openID)}`,
        method: 'GET',
        header: {
          'Authorization': `Bearer ${validToken}`,
          'Content-Type': 'application/json'
        },
        success: (res) => {
          console.log('fetchMembershipExpiry: 响应:', res);
          if (res.statusCode === 200 && res.data && res.data.memberships) {
            const validMemberships = res.data.memberships.filter(m => m.expiryTime && m.expiryTime > Date.now());
            let membershipExpiryDate = '';
            if (validMemberships.length > 0) {
              const latestExpiry = Math.max(...validMemberships.map(m => m.expiryTime));
              membershipExpiryDate = new Date(latestExpiry).toLocaleDateString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit'
              }).replace(/\//g, '-');
            }
            this.setData({ membershipExpiryDate: membershipExpiryDate || '未开通' });
            console.log('fetchMembershipExpiry: 设置 membershipExpiryDate:', membershipExpiryDate || '未开通');
          } else if (res.statusCode === 401) {
            console.log('fetchMembershipExpiry: 401，刷新 token');
            this.refreshToken().then((res) => {
              this.fetchMembershipExpiry(res.openID, res.jwt_token);
            });
          } else {
            console.error('fetchMembershipExpiry: 失败:', res.data);
            this.setData({ membershipExpiryDate: '加载失败' });
          }
        },
        fail: (err) => {
          console.error('fetchMembershipExpiry: 请求失败:', err);
          this.setData({ membershipExpiryDate: '加载失败' });
          wx.showToast({ title: '加载会员信息失败', icon: 'none' });
        }
      });
    }).catch((err) => {
      console.error('fetchMembershipExpiry: Token 验证失败:', err);
      this.setData({ membershipExpiryDate: '加载失败' });
      wx.showToast({ title: '无法验证登录状态', icon: 'none' });
    });
  },

  createPayment(openID, jwtToken, subject, amount, description) {
    this.checkTokenValidity(jwtToken).then((result) => {
      const validToken = result.jwt_token;
      const baseUrl = getApp().getApiBaseUrl();
      console.log('createPayment: 请求 /payment/create-order, token:', validToken.slice(0, 10) + '****');
      const requestData = {
        openID: String(openID),
        subject: String(subject),
        amount: parseFloat(amount),
        description: String(description)
      };
      console.log('createPayment: 支付请求数据:', requestData);
      wx.request({
        url: `${baseUrl}/payment/create-order`,
        method: 'POST',
        header: {
          'Authorization': `Bearer ${validToken}`,
          'Content-Type': 'application/json'
        },
        data: requestData,
        success: (res) => {
          console.log('createPayment: 响应:', res);
          if (res.statusCode === 200 && res.data.success) {
            const orderID = res.data.orderID;
            console.log('createPayment: 支付参数:', res.data.paymentParams);
            wx.requestPayment({
              timeStamp: res.data.paymentParams.timeStamp,
              nonceStr: res.data.paymentParams.nonceStr,
              package: res.data.paymentParams.package,
              signType: res.data.paymentParams.signType,
              paySign: res.data.paymentParams.paySign,
              success: (paymentRes) => {
                // console.log('createPayment: 支付请求发起成功:', paymentRes);
                // wx.showToast({ title: '支付请求已提交', icon: 'loading' });
                this.pollOrderStatus(openID, validToken, orderID);
              },
              fail: (paymentErr) => {
                console.error('createPayment: 支付失败:', paymentErr);
                wx.showToast({ title: '支付失败，请重试', icon: 'none' });
              }
            });
          } else if (res.statusCode === 401) {
            console.log('createPayment: 401，刷新 token');
            this.refreshToken().then((res) => {
              this.createPayment(res.openID, res.jwt_token, subject, amount, description);
            });
          } else {
            console.error('createPayment: 失败:', res.data);
            wx.showToast({ title: res.data.detail || '支付请求失败', icon: 'none' });
          }
        },
        fail: (err) => {
          console.error('createPayment: 请求失败:', err);
          wx.showToast({ title: '请求失败，请检查网络', icon: 'none' });
        }
      });
    }).catch((err) => {
      console.error('createPayment: Token 验证失败:', err);
      wx.showToast({ title: '登录状态失效，请重新登录', icon: 'none' });
    });
  },

  handlePayment(e) {
    const { selectedType } = this.data;
    console.log('handlePayment: 发起支付，selectedType:', selectedType);

    // 映射 selectedType 到服务器期望的 subject 和 amount
    const membershipMap = {
      'firstMonth': { subject: 'First Month Membership', amount: 8.0, description: '首月会员支付' },
      'monthly': { subject: 'Monthly Membership', amount: 28.0, description: '月费会员支付' },
      'yearly': { subject: 'Yearly Membership', amount: 299.0, description: '年费会员支付' }
    };

    if (!selectedType || !membershipMap[selectedType]) {
      console.error('handlePayment: 无效的 selectedType:', selectedType);
      wx.showToast({ title: '请选择有效会员类型', icon: 'none' });
      return;
    }

    const { subject, amount, description } = membershipMap[selectedType];
    console.log('handlePayment: 支付参数，subject:', subject, 'amount:', amount, 'description:', description);

    const app = getApp();
    app.doAutoLogin(true).then((res) => {
      this.createPayment(res.openID, res.jwt_token, subject, amount, description);
    }).catch((err) => {
      console.error('handlePayment: 登录失败:', err);
      wx.showToast({ title: '请先登录', icon: 'none' });
    });
  },

  pollOrderStatus(openID, jwtToken, orderID) {
    let attempts = 0;
    const maxAttempts = 15;
    const interval = 2000;
  
    console.log('pollOrderStatus: 开始轮询订单:', orderID);

    const checkStatus = setInterval(() => {
      this.checkTokenValidity(jwtToken).then((result) => {
        const validToken = result.jwt_token;
        const baseUrl = getApp().getApiBaseUrl();
        console.log('pollOrderStatus: 请求 /payment/order, token:', validToken.slice(0, 10) + '****');
        wx.request({
          url: `${baseUrl}/payment/order?orderID=${orderID}`,
          method: 'GET',
          header: {
            'Authorization': `Bearer ${validToken}`,
            'Content-Type': 'application/json'
          },
          success: (res) => {
            console.log('pollOrderStatus: 响应:', res);
            if (res.statusCode === 200) {
              const { status } = res.data;
              if (status === 'SUCCESS') {
                clearInterval(checkStatus);
                wx.showToast({ title: '支付成功', icon: 'success', duration: 2000 });
                this.checkFirstMonthPurchase(openID, validToken);
                this.fetchMembershipExpiry(openID, validToken);
                // 2秒后跳转到 my 页面
                setTimeout(() => {
                  wx.switchTab({
                    url: '/pages/my/my',
                    success: () => {
                      console.log('跳转到 my 页面成功');
                    },
                    fail: (err) => {
                      console.error('跳转到 my 页面失败:', err);
                    }
                  });
                }, 2000);
              } else if (status === 'FAILED' || attempts >= maxAttempts) {
                clearInterval(checkStatus);
                wx.showToast({ title: '支付未完成，请稍后确认', icon: 'none' });
              }
            } else if (res.statusCode === 401) {
              console.log('pollOrderStatus: 401，刷新 token');
              this.refreshToken().then((res) => {
                this.pollOrderStatus(res.openID, res.jwt_token, orderID);
              });
              clearInterval(checkStatus);
            } else {
              console.error('pollOrderStatus: 失败:', res.data);
            }
          },
          fail: (err) => {
            console.error('pollOrderStatus: 请求失败:', err);
            if (attempts >= maxAttempts) {
              clearInterval(checkStatus);
              wx.showToast({ title: '支付状态未知，请稍后确认', icon: 'none' });
            }
          }
        });
      }).catch((err) => {
        console.error('pollOrderStatus: Token 验证失败:', err);
        clearInterval(checkStatus);
        wx.showToast({ title: '无法验证登录状态', icon: 'none' });
      });
      attempts++;
    }, interval);
  }
});